import React, { Component } from 'react';
import { ImageBackground, ScrollView, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import { TabBarImage, TabBarAnimationImage } from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { statusBarHeight, titleHeight, width, unitWidth } from '../constants/AdapterUtil';
import { MyHeader } from '../components/MyHeader';
import { SubmitButton8, AddButton, ReduceButton, SubmitButton9, SubmitButton10, SubmitButton4, SubmitButton13 } from '../components/Button';
import { api_member_cart_get_list, api_order_detail, api_order_pay, api_order_op_cancel, api_order_op_finish, api_order_op_delete } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import MyListView from '../components/MyListView';
import { DeleteTextView } from '../components/MyTextView';
import { CommonModal2, BottomPayModal, CommonModal3, BottomReasonModal } from '../components/Modal';
import { MeItem, IconItem } from '../components/Item';
import { MyInput1 } from '../components/Input';
import TextUtil from '../constants/TextUtil';
import CommonUtil from '../constants/CommonUtil';
import { show } from '../constants/Toast';
import { contactBrowser } from '../constants/Gobrowser';
import { wxPay } from '../constants/Pay';

export default class GoodsOrderDetailScreen extends Component {
    constructor(props) {
        super(props)
        this.id = this.props.navigation.getParam('id', -1)
        this.isChild = this.props.navigation.getParam('isChild', '0')
        this.state = {
            userInfo: {},
            list: [],

            user_type: global.userInfo.user_type,

            address: '',
            receiver_mobile: '',
            receiver_name: '',
            province: '',
            city: '',
            area: '',

            orderInfo: {},

            mobile: '',//代付手机号
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.refs.MyListView.onRefresh();
        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF7 }}>
                <MyHeader title='订单详情' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                <MyListView
                    style={{ marginBottom: 50 * unitWidth, }}
                    ref='MyListView'
                    ListHeaderComponent={
                        <View>
                            <IconItem
                                icon={
                                    <Image source={require('../res/syss_dddw.png')} style={{ width: 16 * unitWidth, height: 20 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                } text={this.state.address ? (this.state.address + '     ' + this.state.receiver_name + '     ' + this.state.receiver_mobile) : ''} isLast={false} />
                            <IconItem
                                icon={
                                    <Image source={require('../res/gwc_spxqgwc.png')} style={{ width: 17 * unitWidth, height: 17 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                } text='商品详情' isLast={false} />
                        </View>
                    }
                    ListFooterComponent={
                        <View style={{ backgroundColor: Colors.white }}>
                            <IconItem
                                icon={
                                    <Image source={require('../res/ddzx_ddxxic.png')} style={{ width: 17 * unitWidth, height: 18 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                } text='订单信息' isLast={false} />
                            <View style={{ marginLeft: 55 * unitWidth, marginVertical: 8 * unitWidth }}>
                                <Text style={{ fontSize: 14 }}>订单编号：{this.state.orderInfo.ordersn}</Text>
                                <Text style={{ fontSize: 14, marginTop: 5 * unitWidth }}>创建时间：{this.state.orderInfo.createtime}</Text>
                                {this.state.orderInfo.status > 0 ? <Text style={{ fontSize: 14, marginTop: 5 * unitWidth }}>付款时间：{this.state.orderInfo.paytime}</Text> : null}
                                <Text style={{ fontSize: 14, marginTop: 5 * unitWidth }}>订单状态：<Text style={{ color: Colors.colorOrange }}>{CommonUtil.getPayStatusText(this.state.orderInfo.status)}</Text></Text>
                            </View>
                            {this.state.orderInfo.status > 1 ?
                                <View>
                                    <IconItem
                                        icon={
                                            <Image source={require('../res/ddzx_wlxxic.png')} style={{ width: 17 * unitWidth, height: 18 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                        } text='物流信息' isLast={false} />
                                    <View style={{ marginLeft: 55 * unitWidth, marginVertical: 8 * unitWidth }}>
                                        <Text style={{ fontSize: 14 }}>物流公司：{this.state.orderInfo.expresscom}</Text>
                                        <Text style={{ fontSize: 14, marginTop: 5 * unitWidth }}>物流单号：{this.state.orderInfo.expresssn}</Text>
                                    </View>
                                </View> : null}
                        </View>
                    }
                    list={this.state.list}
                    renderItem={this.getItem.bind(this)}
                    getList={this.getData.bind(this)}
                />
                <View style={{
                    flexDirection: 'row', position: 'absolute', bottom: 0,
                    alignItems: 'center', width: width, height: 50 * unitWidth, justifyContent: 'center', backgroundColor: Colors.white
                }}>
                    {this.getStatusBtn(this.state.orderInfo.status)}
                </View>
                <CommonModal2 ref='CommonModal2' title='是否确认删除该订单？' comfirmText='确定' cancelText='取消'
                    cancelClick={() => {

                    }}
                    comfirmClick={() => {
                        this.deleteOrder()
                    }} />
                <BottomPayModal ref='BottomPayModal' onClick={(index) => {
                    this.payOrder(index)
                }} />
                <BottomReasonModal ref='BottomReasonModal' onClick={(index) => {
                    this.cancelOrder();
                }} />
            </View>
        )
    }

    getItem({ item, index }) {
        return (
            <View style={{ alignItems: 'center' }}>
                <View style={{
                    minHeight: 150 * unitWidth,
                    backgroundColor: Colors.white, marginBottom: 8 * unitWidth, paddingHorizontal: 8 * unitWidth
                }}>
                    <View style={{ height: 40 * unitWidth, flexDirection: 'row', alignItems: 'center' }}>
                        <Image style={{
                            width: 12 * unitWidth, height: 11 * unitWidth, marginLeft: 10 * unitWidth
                        }}
                            source={require('../res/gwc_gs.png')} resizeMode='stretch' />
                        <Text style={{ fontSize: 14, color: Colors.black, marginLeft: 5 * unitWidth }}>{item.shopname}</Text>
                        <Image style={{
                            width: 5 * unitWidth, height: 10 * unitWidth, position: 'absolute', right: 0 * unitWidth,
                        }}
                            source={require('../res/me_back.png')} resizeMode='stretch' />
                    </View>
                    <View style={{ backgroundColor: Colors.colorEF, width: 350 * unitWidth, alignSelf: 'center', height: 0.5, }} />
                    <View>
                        {this.getGoodsView(item.goods, index)}
                    </View>
                </View>
            </View>
        )
    }

    getGoodsView(list, index) {
        let views = []
        for (let i = 0, len = list.length; i < len; i++) {
            let item = list[i];
            views.push(
                <View style={{ height: 109 * unitWidth, flexDirection: 'row', alignItems: 'center' }}>
                    <Image style={{
                        width: 110 * unitWidth, height: 80 * unitWidth, marginLeft: 9 * unitWidth
                    }}
                        source={{ uri: item.thumb }} resizeMode='stretch' />
                    <View style={{ marginLeft: 10 * unitWidth }}>
                        <Text style={{ color: Colors.black, fontSize: 14, marginVertical: 4 * unitWidth, width: 190 * unitWidth }}>{item.title}</Text>
                        <View style={{
                            paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, marginTop: 5 * unitWidth,
                            borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start'
                        }}>
                            <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                        </View>
                        <View style={{ alignSelf: 'flex-start', marginTop: 2 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 190 * unitWidth }}>
                            <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                            <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                        </View>
                    </View>
                </View>
            );
        }
        return views
    }

    getStatusBtn(type) {
        if (type == '0') {
            if (global.userInfo.user_type == '3') {
                return null;
            } else {
                return (
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <SubmitButton13 style={{ marginRight: 50 * unitWidth }} text='取消订单' onPress={() => {
                            this.refs.BottomReasonModal.showModal();
                        }} />
                        <SubmitButton4 text='付款' onPress={() => {
                            this.refs.BottomPayModal.showModal();
                        }} />
                    </View>
                )
            }
        } else if (type == '1') {
            return
        } else if (type == '2') {
            if (this.isChild == '1' && global.userInfo.user_type != '3') {
                return null;
            }
            return (
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <SubmitButton4 style={{}} text='确认收货' onPress={() => {
                        this.finishOrder();
                    }} />
                </View>
            )
        } else if (type == '3' || type == '-1') {
            if (this.isChild == '1' && global.userInfo.user_type != '3') {
                return null;
            }
            return (
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <SubmitButton13 style={{}} text='删除订单' onPress={() => {
                        this.refs.CommonModal2.showModal()
                    }} />
                </View>
            )
        }
    }

    getData(page) {
        let params = {
            id: this.id
        }
        postFetch(api_order_detail, params, {
            success: (response) => {
                this.setState({
                    address: response.result.address.address,
                    receiver_mobile: response.result.address.mobile,
                    receiver_name: response.result.address.realname,
                    province: response.result.address.province,
                    city: response.result.address.city,
                    area: response.result.address.area,

                    orderInfo: response.result.order,

                    list: response.result.goods
                }, () => {
                    this.refs.MyListView.onNoMore();
                })
            },
            fail: (response) => {
                this.refs.MyListView.onNoMore();
                show(response.result.message);
            }
        })
    }

    //支付订单
    payOrder(paytype) {
        let params = {
            id: this.id,
        }
        if (paytype == 1) {
            params['paytype'] = 'wechat'
        } else if (paytype == 2) {
            params['paytype'] = 'alipay'
        } else if (paytype == 3) {
            params['paytype'] = 'credit'
        }
        postFetch(api_order_pay, params, {
            success: (response) => {
                if (paytype == 1) {
                    wxPay(response.result.wechat, {
                        success: () => {
                            show('支付成功');
                            this.props.navigation.pop();
                        },
                        fail: () => {

                        }
                    })
                } else if (paytype == 2) {
                    contactBrowser(response.result.alipay.url)
                } else if (paytype == 3) {
                    show('支付成功');
                    this.props.navigation.pop();
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //取消订单
    cancelOrder() {
        let params = {
            id: this.id,
        }
        postFetch(api_order_op_cancel, params, {
            success: (response) => {
                show('取消成功');
                this.props.navigation.pop();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //完成订单
    finishOrder() {
        let params = {
            id: this.id,
        }
        postFetch(api_order_op_finish, params, {
            success: (response) => {
                show('确认成功');
                this.refs.MyListView.onRefresh();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //删除订单
    deleteOrder() {
        let params = {
            id: this.id,
            userdeleted: 1
        }
        postFetch(api_order_op_delete, params, {
            success: (response) => {
                show('删除成功');
                this.props.navigation.pop();
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}